/**
 * 投注的管理
 * context.bets   -- 确认后的
 * context.bets2  -- 本地未确认
 */
var lottery = function() {
    var self = this;

    // 当前的游戏名称
    self.currGame = null;
    self.owner = null;

    /**
     * 回调函数
     */
    self.cb = null;
};
lottery.prototype = {};
lottery.prototype.construct = lottery;

/**
 * 切换游戏
 */
lottery.prototype.switchGame = function(game, owner) {
    var self = this;
    self.currGame = game;
    self.owner = owner;
};

/**
 * 当期投注的期数
 */
lottery.prototype.curr = function() {
    var self = this;
    if (!self.currGame) return;
    var c = Result.curr();
    if (!c) return;
    return c.issue;
};

 // 刷新赔率
 lottery.prototype.refresh_rate = function(callback) {
    var self = this;
    var type = self.currGame;
    if (!type) return;
    var data = context.lottery[type];
    if (!Util.isEmpty(data) && new Date().getTime() - data.time < 10 * 60 * 1000) {
        // 10分钟内不用更新
        if (self.cb) self.cb();
        if (callback) callback();
        return;
    }

    var f = function() {
        CMD.query_lottery_rate(type, self.owner || context.user.user.id, function(r) {
            context.lottery[type] = {
                time: new Date().getTime()
            };
            for (var i in r) {
                context.lottery[type][r[i].target] = r[i];
            }
    
            console.log("获得赔率", type, context.lottery[type]);
            if (self.cb) self.cb();
            if (callback) callback(context.lottery[type]);
        });
    }
    if (context.user && context.user.user) f();
    else {
        ME.query(function() { f(); });
    }
 };

 // 取得投注限额
 lottery.prototype.limit = function(name) {
     var self = this;
     var type = self.currGame;
     if (!type) return [0, 0];
     var m = context.lottery[type];
     if (!m) return [0, 0];

     var v = m.targets;
     if (name) v = m[name];
     if (!v) return [0, 0];
     return [v.min, v.max];
 }

/**
 * 确认投注
 */
lottery.prototype.ok = function(data, issue, source) {
    var self = this;
    var total = 0, count = 0;
    source = source || 'pc';
    for (var k in data) {
        if (k != 'group') {
            count++;
            total += data[k];
        }
    }

    // 余额是否足够
    if (context.user.balance < total) {
        alert2("余额不足，投注失败！", true);
        return;
    }
    if (isEmpty(data)) {
        alert2("下注内容不正确，请重新下注！", true);
        return;
    }

    // 总额度是否超过了？
    var type = self.currGame;
    var t2 = total + self.total(undefined, issue);
    var limit = self.limit();
    if (limit[1] != 0 && limit[1] < t2) {
        alert2("投注总额超过了当期限额，无法投注！", true);
        return;
    }

    // 单注是不是超过了？
    for (var k in data) {
        if (k == 'group') continue;
        t2 = data[k] + self.total(k);
        limit = self.limit(k);
        if (limit[0] > 0 && data[k] < limit[0]) {
            alert2("“" + gameRule.getTargetName(k) + "”不足最低投注限额，无法投注！", true);
            return;
        }
        if (limit[1] > 0 && limit[1] < t2) {
            alert2("“" + gameRule.getTargetName(k) + "”超过单注限额，无法投注！", true);
            return;
        }
    }

    // 注单数是否满足要求
    if (!checkBetCount(count)) return;

    // 由具体游戏判定
    var f = context.global.game[type].checkBetList;
    if (f) {
        if (!f(type, issue, data)) {
            console.log("不允许下注！");
            return;
        }
    }

    reset_counter();
    console.log("请求投注", data, total);
    data.type = type;
    data.issue = issue;
    data.source = source;
    var url = Util.getUrl("bet/create");
    startLoading();
    CMD.create_bet(type, issue, data, function(r) {
        stopLoading();
        if (!isEmpty(r.failures)) {
            alert2("下注失败！", true);
            return;
        }

        if (context.bets[type])
            context.bets[type][issue] = {};
        
        // 更新余额的信息
        if (!Util.isEmpty(r.accounts)) {
            for (var i in r.accounts) {
                if (r.accounts[i].owner != '') continue;
                var o = r.accounts[i];
                context.user.balance = o.balance;
                context.user.pending = o.pending;
            }
        }
        self.refresh_uncheck();
        if (self.cb) self.cb();
        if (ME && ME.cb) ME.cb();
        if (window.layer && layer.alert) {
            layer.alert("下注成功，等待开奖", {
                icon: 1,
                time: 2000,
            });
        }
        else
            alert2("下注成功，等待开奖");
        setTimeout(function() {
            // 自动关闭
            if ($("#clue").css("display") == 'block') {
                $("#clue").modal('close');
            }
        }, 2000);
    }, function(r) {
        stopLoading();
        alert2("下注失败！", true);
    });
};

/**
 * 计算投注总额
 */
lottery.prototype.total = function(name, issue) {
    var self = this;
    var bets = context.bets[self.currGame];
    if (bets) bets = bets[issue] || {};
    else bets = {};
    var total = 0;

    if (!name) {
        // 取得本期的投注总额
        for (var k in bets) {
            total += bets[k].amount;
        }
    }
    else {
        for (var k in bets) {
            if (bets[k].target == name)
                total += bets[k].amount;
        }
    }
    return total;
}

/**
 * 计算投注的注单数
 */
lottery.prototype.totalCount = function(issue) {
    var self = this;
    var bets = context.bets[self.currGame];
    if (bets) bets = bets[issue] || {};
    else bets = {};
    var total = 0;
    for (var k in bets) {
            total++;
    }
    return total;
}

/**
 * 拉取某类投注列表（冒号之前）
 */
lottery.prototype.queryClassify = function(name, issue) {
    var self = this;
    var bets = context.bets[self.currGame];
    if (bets) bets = bets[issue] || {};
    else bets = {};
    var list = [];
    for (var k in bets) {
        if (k.startsWith(name + ":")) {
            list.push(bets[k]);
        }
    }
    return list;
};

// 更新投注的信息(未结算，所有游戏)
lottery.prototype.refresh_uncheck = function(cb) {
    var self = this;
    CMD.bet_incomplete(function(r) {
        context.bets = {};
        self.set_bet_data(r);
        if (self.cb) self.cb();
        if (cb) cb();
    });
};

// 取得今日已结算的信息
lottery.prototype.today = function(callback) {
    var self = this;
    CMD.bet_today(self.currGame, function(r) {
        callback(r || []);
    });
};

// 设置投注列表的数据
lottery.prototype.set_bet_data = function(list) {
    for (var k in list) {
        var data = list[k];
        var type = data.type;
        var issue = data.issue;
        if (data.state == 1) continue;
        if (!context.bets[type]) context.bets[type] = {};
        if (!context.bets[type][issue]) context.bets[type][issue] = [];
        context.bets[type][issue].push(data);
    }
};

// 合并同一组的投注记录
lottery.prototype.combineGroup = function(list) {
    // 对同一组的信息做下合并
    var data = [];
    for (var i in list) {
        var o = list[i];
        var group = o.group;
        if (!group) {
            data.push(Util.copyObject(o));
            continue;
        }

        var find = false;
        for (var j in data) {
            if (data[j].group == group) {
                data[j].amount += o.amount;
                data[j].profit += o.profit;
                find = true;
                break;
            }
        }
        if (!find) data.push(Util.copyObject(o));
    }
    return data;
}

window.Lottery = new lottery();
